package net.huadong.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * BIO 消息处理
 * ws
 */
public class BioTimeServerHandler implements Runnable {
    private Socket socket;

    public BioTimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            //初始化输入流
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            //初始化输出流
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String body = null;
            while (true) {
                body = in.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("服务收到指令：" + body);

                if ("QUERY_TIME_ORDER".equals(body)) {
                    //输出结果
                    out.println(new Date(System.currentTimeMillis()).toString());
                } else {
                    out.println("BAD ORDER");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                this.socket = null;
            }


        }
    }
}
